from fastapi import Request
from tortoise.transactions import in_transaction

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.token import Token
from util.str import Str

async def CreateSongSheet(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            title = body.get("title")
            if Str.isBlank(title):
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            token = req.headers.get("token")
            if Token().verify_token(token) == None:
                return Result.error(BaseEnum.TOKEN_INVALID_ERROR)
            
            user = await UserService.getUserByToken(token)
            if user == None:
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
            
            res = await SongService.createSongSheet({
                "user_id": user.id,
                "title": title,
                "description": '作者很懒，什么也没说'
            })

            return Result.success(res)
    except Exception as e:
        Log.error('创建 song sheet 异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)